package com.chainyoung.component_tmperson.ui.fragment;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.chainyoung.common.appcommon.entity.CommonList;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonFragmentComponent;
import com.chainyoung.component_tmperson.di.module.PersonFragmentModule;
import com.chainyoung.component_tmperson.entity.PurseAddrItem;
import com.chainyoung.component_tmperson.ui.activity.cloudwallet.MyPurseAddrActivity;
import com.chainyoung.component_tmperson.ui.adapter.MyPurseAddrAdapter;
import com.chainyoung.component_tmperson.ui.mvp.contract.GetPurseListContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.GetPurseListPresenter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;

import static android.app.Activity.RESULT_OK;


public class MyPurseAddrListFragment extends BaseFragment<GetPurseListPresenter> implements GetPurseListContract.View {


    @BindView(R2.id.recycler_view)
    SwipeMenuRecyclerView recyclerView;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;


    public static final String TYPE_CLOUD = "cloud";
    public static final String TYPE_LOCAl = "hd";

    private String type;

    private MyPurseAddrAdapter mAdapter;
    private List<PurseAddrItem> mData = new ArrayList<>();
    private boolean isCanloadMore;
    protected int pageNo = 1;
    private int removedPosition;

    private ClipboardManager clipboardManager;
    private ClipData mClipData;


    public static MyPurseAddrListFragment newInstance(String type) {
        MyPurseAddrListFragment fragment = new MyPurseAddrListFragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerPersonFragmentComponent.builder()
                .appComponent(appComponent)
                .personFragmentModule(new PersonFragmentModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getString("type");
        }
    }

    @Override
    protected boolean useLoadSir() {
        return true;
    }

    @Override
    protected void onPageRetry(View v) {
        super.onPageRetry(v);
        pageNo = 1;
        loadData();
    }


    @Override
    protected void initUi() {
        super.initUi();
        clipboardManager = (ClipboardManager) mContext.getSystemService(mContext.CLIPBOARD_SERVICE);
        initRvList();
    }


    private void initRvList() {
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        DividerItemDecoration itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.shape_divider_gray));
        recyclerView.addItemDecoration(itemDecoration);
        // recyclerView.setSwipeMenuCreator(mSwipeMenuCreator);
        //  recyclerView.setSwipeMenuItemClickListener(mMenuItemClickListener);
        mAdapter = new MyPurseAddrAdapter(mContext, mData);
        recyclerView.setAdapter(mAdapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isCanloadMore) {
                    pageNo++;
                    loadData();
                } else {
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                loadData();
            }
        });
        mAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int p = (int) v.getTag();
                PurseAddrItem item = mData.get(p);
                if (((MyPurseAddrActivity) getActivity()).isFromCloudSelect()
                        || ((MyPurseAddrActivity) getActivity()).isFromHdSelect()) {
                    Intent intent = new Intent();
                    intent.putExtra("data", item.getAddr());
                    (getActivity()).setResult(RESULT_OK, intent);
                    (getActivity()).finish();
                } else {
                    String text = item.getAddr();
                    //创建一个新的文本clip对象
                    mClipData = ClipData.newPlainText("block", text);
                    //把clip对象放在剪贴板中
                    clipboardManager.setPrimaryClip(mClipData);
                    ToastUtil.showToast(mContext.getString(R.string.tmperson_copy_success));
                }
            }
        });

        mAdapter.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                final int p = (int) v.getTag();
                removedPosition = p;
                final PurseAddrItem item = mData.get(p);
                android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(mContext);
                builder.setMessage("确认删除吗？")
                        .setPositiveButton(mContext.getString(R.string.confirm), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                delAddr(item.getId(), p);
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton(mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                builder.create();
                builder.show();

                return true;
            }
        });


    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onFirstUserVisible() {
        pageNo = 1;
        loadData();
    }


    @Override
    public void onUserVisible() {
        super.onUserVisible();
        pageNo = 1;
        loadData();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_fragment_my_purse_list;
    }


    //---------------------------------------------------------------网络请求---------------------------------------------------

    private void loadData() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("page", pageNo);
        map.put("limit", LibConstant.PAGE_SIZ);
        map.put("wallet_type", type);
        if (type.equals(TYPE_LOCAl)) {
            map.put("coin", "eth");
        }
        mPresenter.getPurseAddrList(map);
    }

    private void delAddr(String id, int position) {
        removedPosition = position;
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("address_id", id);
        mPresenter.delPurseAddr(map);
    }

    @Override
    public void onGetPurseListSuccess(CommonList<PurseAddrItem> data) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (pageNo == 1) {
            mData.clear();
        }
        if (data == null) {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
            if (pageNo == 1) {
                showPageEmpty();
            }
            return;
        }
        mData.addAll(data.getList());
        if (data.getPage() < data.getTotal_page()) {
            isCanloadMore = true;
            refreshLayout.setEnableLoadMore(true);
        } else {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
        }

        if (mData.isEmpty()) {
            showPageEmpty();
        } else {
            showPageContent();
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetPurseListFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        showPageError();
    }

    @Override
    public void onDelPurseAddrSuccessed() {
        mData.remove(removedPosition);
        mAdapter.notifyItemRemoved(removedPosition);
        mAdapter.notifyItemRangeChanged(removedPosition, mData.size());
        if (mData.isEmpty()) {
            showPageEmpty();
        }
    }


}
